package chat.network.tcp;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.os.Process;
import android.support.annotation.Nullable;
import android.util.Log;

import com.whu.zj.R;

import main.activity.MainActivity;

/**
 * Created by Administrator on 2015/12/29.
 */
public class PushService extends Service {

    public static String ACTION_CONNECTION = "ACTION_CONNECTION";
    public static String ACTION_DESTORY = "ACTION_DESTORY";
    public static String SERVICE_ACTION = "SERVICE_ACTION";

    public static PushService pushService;

    static ReceiveThread receiveThread;


    @Override
    public void onCreate() {
        super.onCreate();
        pushService = PushService.this;
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//        PendingIntent pendingIntent2 = PendingIntent.getService(this, 0, new Intent(this, MainActivity.class), 0);
        // API11之后才支持
//        Notification notify2 = new Notification.Builder(this)
//                .setSmallIcon(R.drawable.desk) // 设置状态栏中的小图片，尺寸一般建议在24×24，这个图片同样也是在下拉状态栏中所显示，如果在那里需要更换更大的图片，可以使用setLargeIcon(Bitmap
//                .setTicker("启动推送服务:")// 设置在status
//                .setContentTitle("推送服务")// 设置在下拉status
//                .setContentText("保证即时服务")// TextView中显示的详细内容
//                .setContentIntent(pendingIntent2) // 关联PendingIntent
//                .getNotification(); // 需要注意build()是在API level
//
//        notify2.flags |= Notification.FLAG_AUTO_CANCEL;
//
//        startForeground(Integer.MIN_VALUE, notify2);

        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, TimeReceiver.class);
        PendingIntent pendingIntent=PendingIntent.getBroadcast(this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 300000, pendingIntent);
        // 初始化定时器
        TimeCheck.share().init();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null) {
            intent = new Intent(ACTION_CONNECTION);
            intent.putExtra(SERVICE_ACTION, ACTION_CONNECTION);
        }
        String action = intent.getStringExtra(SERVICE_ACTION);
        mydealed(action);
        return 3;
    }

    // 处理接收到的数据
    public void mydealed(String action) {
        Log.i("收到的命令:",action+"");
        // 建立连接
        if (ACTION_CONNECTION.equals(action) ) {
            if (PushService.netWorkAvailable(this)) {

                if (receiveThread == null || receiveThread.isStop) {
                    receiveThread = new ReceiveThread(this);
                    receiveThread.start();
                }
                else if (receiveThread.isRunning)
                {
                    // 连接正常，检查超时
                    if (TimeCheck.share().isTimeOut()) {
                        Log.i("客户端超时","关闭连接");
                        receiveThread.setStop(true);
                        TimeCheck.share().setChecekedTime();
                    }
                }

            } else {
                // 网络不可用，重试也无意义
            }

        }

         // 关闭程序
        if (ACTION_DESTORY.equals(action)) {

            this.stopSelf();
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(this, TimeReceiver.class);
            PendingIntent pendingIntent=PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            alarmManager.cancel(pendingIntent);
            Process.killProcess(Process.myPid());
        }

    }

    @Override
    public void onDestroy() {

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    // 发送消息到pushService
    public static void sendMsgToPush(String action)
    {
        if (pushService !=null)
        {
            pushService.mydealed(action);
        }
    }

    // 检查网络是否可用
    public static boolean netWorkAvailable(Context context) {
        try {
            ConnectivityManager nw = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = nw.getActiveNetworkInfo();
            return networkInfo != null;
        } catch (Exception var3) {
            return false;
        }
    }




}
